package com.pubinfo.passbook.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pubinfo.passbook.common.entity.TFileElectronicFtp;
import com.pubinfo.passbook.common.entity.TFileInfo;
import com.pubinfo.passbook.common.entity.TPassbook;
import com.pubinfo.passbook.common.entity.TSourceArtificial;
import com.pubinfo.passbook.common.mapper.TSourceArtificialMapper;
import com.pubinfo.passbook.common.model.dto.MDM.TSourceArtificialParam;
import com.pubinfo.passbook.common.model.dto.file.ArtificialParam;
import com.pubinfo.passbook.common.model.vo.rule.TSourceArtificialDetailVo;
import com.pubinfo.passbook.common.service.master.ITSourceArtificialService;
import com.pubinfo.passbook.common.service.master.TPassbookService;
import com.pubinfo.passbook.data.service.ArtificialService;
import com.pubinfo.passbook.data.service.TFileInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ArtificialServiceImpl implements ArtificialService {
  @Autowired
  TSourceArtificialMapper artificialMapper;
  @Autowired
  ITSourceArtificialService itSourceArtificialService;
  @Autowired
  TFileInfoService tFileInfoService;
  @Autowired
  TPassbookService passbookService;
  
  @Override
  public Boolean saveArtificial(ArtificialParam artificialParam) throws IOException {
    TSourceArtificial tSourceArtificial = artificialParam.getTSourceArtificial();
    //先保存数量、票据总额和核定总额
    tSourceArtificial.setSystemIsLocked("N");
    itSourceArtificialService.save(tSourceArtificial);
    if (!CollectionUtils.isEmpty(artificialParam.getInvoiceIds())) {
    
      UpdateWrapper<TPassbook> updateWrapper = new UpdateWrapper<>();
      updateWrapper.set("artificial_id", tSourceArtificial.getId());
      updateWrapper.set("system_is_locked", "Y");//锁定票据
      updateWrapper.in("id", artificialParam.getInvoiceIds());
      passbookService.update(updateWrapper);
    }
    //将附件保存
    return tFileInfoService.uploadArtificial(artificialParam, tSourceArtificial.getId());
  }
  @Override
  public IPage<TSourceArtificialDetailVo> selectArtificialByCreateUser(TSourceArtificialParam param) {
    return itSourceArtificialService.listArtificial(param);
  }
  
  @Override
  public List<TFileInfo> selectTfileInfoByArtificialId(String artificialId) {
    return tFileInfoService.selectByArtificialId(artificialId);
  }
  
  @Override
  public List<TFileElectronicFtp> findFileFtpByArtificialList(List<TSourceArtificial> artificialList) {
    if (CollectionUtils.isEmpty(artificialList)) {
      return null;
    }
    List<String> ids = artificialList.stream().map(TSourceArtificial::getId).collect(Collectors.toList());
    return artificialMapper.findFileFtpByArtificiaIds(ids);
  }
}
